<template>
  <div style="position: relative">
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane
        v-for="(label, key) in data.tabConfig"
        :key="key"
        :label="label"
        :name="key"
      >
      </el-tab-pane>
    </el-tabs>
    <div class="func" v-if="data.approveParams.status == 0">
      自动审批：
      <!-- <el-button
        :icon="data.autoApproveParams.value == '1' ? Open : TurnOff"
        @click="changeAutoApprove"
        >{{
          data.autoApproveParams.value == "1" ? "关闭自动审批" : "开启自动审批"
        }}</el-button
      > -->
      <el-switch
        v-model="data.autoApproveParams.value"
        style="--el-switch-off-color: #bfbfbf; --el-switch-on-color: #a939a9"
        active-value="1"
        inactive-value="0"
        active-text="开启"
        inactive-text="关闭"
        inline-prompt
        @change="changeAutoApprove"
      ></el-switch>
    </div>
    <HETTable1
      ref="approveTable"
      v-if="tableFlag"
      :tableData="data.tableData"
      :tHead="data.tHead"
      :total="data.total"
      @getTableData="getGuardApprove"
    >
      <template #ip>
        <el-table-column label="IP">
          <template #default="scope">
            {{ scope.row.ip ? scope.row.ip : "—" }}
          </template>
        </el-table-column>
      </template>
      <template #mac>
        <el-table-column label="MAC">
          <template #default="scope">
            {{ scope.row.mac ? scope.row.mac : "—" }}
          </template>
        </el-table-column>
      </template>
      <template #approveUser>
        <el-table-column
          label="审批人"
          v-if="data.approveParams.status === 1 || data.approveParams.status === 2"
        >
          <template #default="scope">
            {{ scope.row.approveUser }}
          </template>
        </el-table-column>
      </template>
      <template #approveTime>
        <el-table-column
          label="审批时间"
          v-if="data.approveParams.status === 1 || data.approveParams.status === 2"
        >
          <template #default="scope">
            {{ scope.row.approveTime }}
          </template>
        </el-table-column>
      </template>
      <template #expireTime>
        <el-table-column
          label="过期时间"
          v-if="data.approveParams.status === 0 || data.approveParams.status === 3"
        >
          <template #default="scope">
            {{ scope.row.expireTime }}
          </template>
        </el-table-column>
      </template>
      <template #FailureCountdown>
        <el-table-column label="失效倒计时" v-if="data.approveParams.status === 0">
          <template #default="scope">
            {{ timeToFormat(scope.row.failureTime) }}
          </template>
        </el-table-column>
      </template>
      <template #operation>
        <el-table-column label="操作" v-if="data.approveParams.status === 0">
          <template #default="scope">
            <el-popconfirm
              confirm-button-text="确定"
              cancel-button-text="取消"
              title="你确定要审批该设备？"
              @confirm="approve(scope.row.regId)"
            >
              <template #reference>
                <span class="mr-6">
                  <el-text class="cursor-pointer" type="primary">审批</el-text>
                </span>
              </template>
            </el-popconfirm>
            <el-popconfirm
              confirm-button-text="确定"
              cancel-button-text="取消"
              title="你确定要拒绝审批该设备？"
              @confirm="refuse(scope.row.regId)"
            >
              <template #reference>
                <el-text class="cursor-pointer" type="primary">拒绝</el-text>
              </template>
            </el-popconfirm>
            <!-- <el-button @click="approve(scope.row.regId)">审批</el-button> -->
            <!-- <el-button @click="refuse(scope.row.regId)">拒绝</el-button> -->
          </template>
        </el-table-column>
        <el-table-column label="操作" v-if="data.approveParams.status === 2">
          <template #default="scope">
            <el-popconfirm
              confirm-button-text="确定"
              cancel-button-text="取消"
              title="你确定要删除该条记录？"
              @confirm="deleteRefluse(scope.row.regId)"
            >
              <template #reference>
                <el-text class="cursor-pointer" type="primary">删除</el-text>
              </template>
            </el-popconfirm>
            <!-- <el-button @click="deleteRefluse(scope.row.regId)">删除</el-button> -->
          </template>
        </el-table-column>
      </template>
    </HETTable1>
  </div>
</template>

<script setup>
import { ref, reactive, computed, nextTick, onMounted, markRaw, watch } from "vue";
import { TurnOff, Open } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  req_getGuardApproveCount,
  req_getGuardApprove,
  req_guardApprove,
  req_getAutoApproveStatus,
  req_setAutoApproveStatus,
  req_guardApproveDelete,
} from "~/utils/axios/index.js";
import { useRouter } from "vue-router";
let $router = useRouter();
const approveTable = ref();
const activeName = ref("notApprovedVue");
const tableFlag = ref(true);

const changeAutoApprove = (val) => {
  let params = {
    name: data.autoApproveParams.name,
    value: val,
  };
  req_setAutoApproveStatus(params).then((res) => {
    if (res.data.succeed) {
      ElMessage.success("操作成功");
    } else {
      ElMessage.error("操作失败");
    }
    getAutoApproveStatus();
  });
};
const data = reactive({
  tabConfig: {
    notApprovedVue: "未审批",
    approvedVue: "已审批",
    rejectedVue: "已拒绝",
    expiredVue: "已过期",
  },
  tHead: [
    {
      label: "名称",
      prop: "name",
      isCustom: false,
      width: 200,
    },
    {
      label: "IP",
      prop: "ip",
      isCustom: true,
      slotName: "ip",
    },
    {
      label: "MAC",
      prop: "mac",
      isCustom: true,
      slotName: "mac",
    },
    {
      label: "请求时间",
      prop: "createTime",
      isCustom: false,
    },
    {
      label: "审批人",
      prop: "approveUser",
      isCustom: true,
      slotName: "approveUser",
    },
    {
      label: "审批时间",
      prop: "approveTime",
      isCustom: true,
      slotName: "approveTime",
    },
    {
      label: "过期时间",
      prop: "expireTime",
      isCustom: true,
      slotName: "expireTime",
    },
    {
      label: "失效倒计时",
      prop: "FailureCountdown",
      isCustom: true,
      slotName: "FailureCountdown",
    },
    {
      label: "操作",
      prop: "operation",
      isCustom: true,
      slotName: "operation",
    },
  ],
  tableData: [],
  total: null,
  approveParams: {
    type: 0, // 类型 1:卸载审批 0:接入审批
    status: 0, // 审批状态 0-未审批 1-已审批 2-已拒绝 3-已过期
  },
  autoApproveParams: {
    name: "LOAD_AUTO_APPROVE", // 接入审批：LOAD_AUTO_APPROVE 卸载审批：DELETE_AUTO_APPROVE
    value: "0", // 1：开启自动审批 0：关闭自动审批
  },
});
const failureCountdown = (row) => {
  let endTime = new Date(row.expireTime).getTime();
  let now = new Date().getTime();
  let distance = endTime - now;
  row.failureTime = distance;
  row.countDown = setInterval(() => {
    row.failureTime -= 1000;
    if (row.failureTime < 0) {
      clearInterval(row.countDown);
    }
  }, 1000);
};
const timeToFormat = computed(() => (time) => {
  if (time > 0) {
    let hours = Math.floor(time / (1000 * 60 * 60));
    let minutes = Math.floor((time % (1000 * 60 * 60)) / (1000 * 60));
    let seconds = Math.floor((time % (1000 * 60)) / 1000);
    return hours + "时 " + minutes + "分 " + seconds + "秒 ";
  } else {
    return "已过期";
  }
});

const handleClick = (tab, event) => {
  tableFlag.value = false;
  let status;
  switch (tab.props.name) {
    case "notApprovedVue":
      status = 0;
      break;
    case "approvedVue":
      status = 1;
      break;
    case "rejectedVue":
      status = 2;
      break;
    case "expiredVue":
      status = 3;
      break;
  }
  data.approveParams.status = status;
  nextTick(() => {
    tableFlag.value = true;
  });
};
const getGuardApprove = async (initTableParams) => {
  approveTable.value.loading();
  let approveParams = {
    ...data.approveParams,
    start: initTableParams.page * initTableParams.size,
    size: initTableParams.size,
  };
  const { data: count } = await req_getGuardApproveCount(data.approveParams);
  const { data: res } = await req_getGuardApprove(approveParams);
  approveTable.value.finish();
  data.total = res.total;
  data.tableData = res.data;
  data.tableData.forEach((item) => {
    failureCountdown(item);
  });
};
const approve = (reg_id) => {
  let params = {
    regId: reg_id,
    status: 1,
  };
  req_guardApprove(params).then((res) => {
    res.data.succeed ? ElMessage.success("审批通过") : ElMessage.error("操作失败");
    approveTable.value.getTableData();
  });
};
const deleteRefluse = (reg_id) => {
  let params = {
    regId: reg_id,
  };
  req_guardApproveDelete(params).then((res) => {
    res.data.succeed ? ElMessage.success("操作成功") : ElMessage.error("操作失败");
    approveTable.value.getTableData();
  });
};
const refuse = (reg_id) => {
  let params = {
    regId: reg_id,
    status: 2,
  };
  req_guardApprove(params).then((res) => {
    res.data.succeed ? ElMessage.success("已拒绝") : ElMessage.error("操作失败");
    approveTable.value.getTableData();
  });
};
const getAutoApproveStatus = async () => {
  const { data: res } = await req_getAutoApproveStatus(data.autoApproveParams.name);
  data.autoApproveParams.value = res.value;
};
getAutoApproveStatus();
watch(
  () => $router.currentRoute.value.path,
  (path, oldPath) => {
    if (path == "/approval") {
      data.approveParams.type = 0;
      data.autoApproveParams.name = "LOAD_AUTO_APPROVE";
    } else if (path == "/unload") {
      data.approveParams.type = 1;
      data.autoApproveParams.name = "DELETE_AUTO_APPROVE";
    }
    tableFlag.value = false;
    activeName.value = "notApprovedVue";
    data.approveParams.status = 0;

    nextTick(() => {
      tableFlag.value = true;
    });
  },
  { immediate: true }
);
</script>

<style lang="scss" scoped>
.func {
  position: absolute;
  top: 80px;
  left: 16px;
  font-size: 16px;
}
</style>
